const API_BASE_URL = 'https://your-api-domain';
const Storage = require('../../utils/storage');

Page({
  data: {
    userAvatar: '',
    userName: '',
    userGender: '',
    userAge: '',
    questionTime: '',
    question: '',
    answers: [],
    viewCount: 0,
    loading: true,
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loadingMore: false
  },

  onLoad(options) {
    if (!options.id) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }
    this.questionId = options.id;
    this.fetchQuestionData(options.id);
  },

  fetchQuestionData(id) {
    this.showLoading();
    wx.request({
      url: `${API_BASE_URL}/api/v1/questions/${id}`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': Storage.getAuthToken()
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const data = res.data.data;
          if (this.validateData(data)) {
            this.setData({
              userAvatar: data.userAvatar,
              userName: this.maskPhoneNumber(data.userId),
              userGender: data.userGender,
              userAge: data.userAge,
              questionTime: this.formatTime(data.date),
              question: data.question,
              viewCount: data.viewCount,
              loading: false
            });
            this.fetchAnswers();
          }
        } else {
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
          this.useMockData();
        }
      },
      fail: (err) => {
        console.error('获取问答详情失败：', err);
        this.useMockData();
      },
      complete: () => {
        this.hideLoading();
      }
    });
  },

  fetchAnswers() {
    if (!this.data.hasMore || this.data.loadingMore) return;

    this.setData({ loadingMore: true });
    wx.request({
      url: `${API_BASE_URL}/api/v1/questions/${this.questionId}/answers`,
      method: 'GET',
      data: {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      },
      header: {
        'content-type': 'application/json',
        'Authorization': Storage.getAuthToken()
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const newAnswers = res.data.data.list || [];
          const total = res.data.data.total || 0;
          
          this.setData({
            answers: [...this.data.answers, ...newAnswers],
            pageNum: this.data.pageNum + 1,
            hasMore: (this.data.answers.length + newAnswers.length) < total
          });
        } else {
          this.useMockMoreAnswers();
        }
      },
      fail: (err) => {
        console.error('获取答案列表失败：', err);
        this.useMockMoreAnswers();
      },
      complete: () => {
        this.setData({ loadingMore: false });
      }
    });
  },

  useMockMoreAnswers() {
    if (this.data.pageNum >= 4) {
      this.setData({
        hasMore: false
      });
      return;
    }

    const mockAnswers = [
      {
        id: this.data.answers.length + 1,
        doctorName: '王医生',
        department: '神经内科',
        doctorTitle: '主任医师',
        hospitalLevel: '三甲',
        doctorAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
        answer: '建议：\n1. 保持良好的作息习惯\n2. 适当运动，缓解压力\n3. 定期体检，监测血压',
        time: '2024-01-21',
        likeCount: 76
      }
    ];

    this.setData({
      answers: [...this.data.answers, ...mockAnswers],
      pageNum: this.data.pageNum + 1,
      hasMore: this.data.pageNum < 4
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.fetchAnswers();
    }
  },

  useMockData() {
    const mockData = {
      userAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
      userName: this.maskPhoneNumber('13800138000'),
      userGender: '女',
      userAge: '28',
      questionTime: '2024-01-20',
      question: {
        content: '最近总是感觉头晕头痛，血压偏高，该怎么调理？平时工作压力比较大，熬夜比较多。',
        tags: ['头痛', '头晕', '高血压']
      },
      viewCount: 1234,
      answers: [
        {
          id: 1,
          doctorName: '张医生',
          department: '心内科',
          doctorTitle: '主任医师',
          hospitalLevel: '三甲',
          doctorAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
          answer: '根据您描述的症状，建议从以下几个方面进行调理：\n1. 作息调整：保证充足睡眠，最好在23点前入睡，避免长期熬夜。\n2. 饮食调整清淡饮食，控制盐分摄入，多食用富含钾的蔬菜水果。\n3. 运动建议：适当进行有氧运动，如散步、慢跑等，但不要剧烈运动。\n4. 压力管理：建议通过运动、听音乐等方式缓解压力，必要时可以寻求心理咨询。\n建议您先到医院进行详细检查，明确是否存在高血压等问题，再进行针对性治疗。',
          time: '2024-01-21',
          likeCount: 123
        },
        {
          id: 2,
          doctorName: '李医生',
          department: '神经内科',
          doctorTitle: '副主任医师',
          hospitalLevel: '三甲',
          doctorAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
          answer: '头痛可能与多种因素有关，需要注意以下几点：\n1. 建议测量血压，记录血压变化情况。\n2. 调整作息时间，避免长期熬夜工作。\n3. 工作时注意适当休息，每隔1小时起来活动5-10分钟。\n4. 如果问题持续，建议到神经内科就医，进行头部CT或核磁共振检查，排除器质性病变。',
          time: '2024-01-21',
          likeCount: 89
        }
      ]
    };

    this.setData({
      userAvatar: mockData.userAvatar,
      userName: mockData.userName,
      userGender: mockData.userGender,
      userAge: mockData.userAge,
      questionTime: this.formatTime(mockData.questionTime),
      question: mockData.question,
      viewCount: mockData.viewCount,
      answers: mockData.answers,
      pageNum: 1,
      hasMore: true
    });
  },

  maskPhoneNumber(phone) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  },

  showLoading() {
    wx.showLoading({
      title: '加载中...'
    });
  },

  hideLoading() {
    wx.hideLoading();
  },

  validateData(data) {
    return data && data.userId && data.question && Array.isArray(data.answers);
  },

  formatTime(dateStr) {
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  },

  formatTimeAgo(dateStr) {
    const now = new Date();
    const date = new Date(dateStr);
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  },

  onFabClick() {
    wx.navigateTo({
      url: '/pages/consult-form/index',
      fail: (err) => {
        console.error('跳转失败：', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }
}); 